package cn.com.jcoo.generator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class CodeGenerator {
	static Scanner scanner = new Scanner(System.in);

	public static String scannerNext(String message) {
		System.out.println(message);
		String nextLine = scanner.nextLine();
		if (StringUtils.isBlank(nextLine)) {
			// 如果输入空行继续等待
			return scanner.next();
		}
		return nextLine;
	}

	public static void main(String[] args) {
		String url = scannerNext("url(eg. jdbc:mysql://127.0.0.1:3306/schemaName):");
		String username = scannerNext("username(eg. root):");
		String password = scannerNext("password(eg. 123456):");
		String schemaName = scannerNext("schemaName(eg. dbname):");
		DataSourceConfig.Builder cfgBuilder = new DataSourceConfig.Builder(url, username,
				password).schema(schemaName).keyWordsHandler(new MySqlKeyWordsHandler());
		FastAutoGenerator.create(cfgBuilder)
				// 全局配置
				.globalConfig((scanner, builder) -> builder
						.author(scanner.apply("请输入作者名称？")).enableSwagger()
						.outputDir(scanner.apply("请指定输出目录？") + "/src/main/java")// 指定输出目录
						.disableOpenDir() // 禁止打开输出目录
				)
				// 包配置
				.packageConfig(
						(scanner, builder) -> builder.parent(scanner.apply("请输入包名？"))
								.moduleName(scanner.apply("请输入模块名？"))
								.entity(scanner.apply("请输入实体包名？") + ".model")
								// 设置mapperXml生成路径
								.pathInfo(Collections.singletonMap(OutputFile.xml,
										scanner.apply("请指定XML输出目录？")
												+ "/src/main/resources/mapper")))
				// 策略配置
				.strategyConfig((scanner, builder) -> builder
						.addInclude(getTables(scanner.apply("请输入表名，多个英文逗号分隔？所有输入 all")))
						.controllerBuilder().enableFileOverride().enableRestStyle()
						.enableHyphenStyle().entityBuilder().enableLombok()
						.addTableFills(new Column("create_time", FieldFill.INSERT))
						.build())
				/*
				 * 模板引擎配置，默认 Velocity 可选模板引擎 Beetl 或 Freemarker .templateEngine(new
				 * BeetlTemplateEngine()) .templateEngine(new FreemarkerTemplateEngine())
				 */
				.execute();
	}

	// 处理 all 情况
	protected static List<String> getTables(String tables) {
		return "all".equals(tables) ? Collections.emptyList()
				: Arrays.asList(tables.split(","));
	}
}
